package com.lqk.demo.atomic.unsafe;

import lombok.Data;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author lqk
 * @date 2022/1/4 14:56
 */
public class TestUnsafeCas {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);  // 允许访问私有成员变量
        Unsafe unsafe = (Unsafe)theUnsafe.get(null);

        System.out.println(unsafe);

        // 1. 获取域(属性)的偏移地址
        long idOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("id"));
        long nameOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));

        Student student = new Student();
        // 2. 执行 cas 操作
        unsafe.compareAndSwapInt(student,idOffset,0,1);
        unsafe.compareAndSwapObject(student,nameOffset,null,"张三");

        System.out.println(student);

    }

}

@Data
class Student {
    volatile int id;
    volatile String name;
}